#include "proto/codec.h"
#include "proto/dispatcher.h"

#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpServer.h"

#include "request/request.pb.h"
#include "response/response.pb.h"

class Server
{
public:
    typedef std::shared_ptr<TranslateRequest> TranslateRequestPtr;
    typedef std::shared_ptr<CalculateRequest> CalculateRequestPtr;

public:
    Server(int port, const std::string& ip = "0.0.0.0") :
        _server(&_base_loop, muduo::net::InetAddress(ip, port), "server", muduo::net::TcpServer::kReusePort),
        _dispatcher(std::bind(&Server::onUnknownMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)),
        _codec(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
    {
        // 1. 给分发器注册业务处理函数
        _dispatcher.registerMessageCallback<TranslateRequest>(std::bind(&Server::onTranslateMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        _dispatcher.registerMessageCallback<CalculateRequest>(std::bind(&Server::onCalculateMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        // 2. 给服务器设置连接建立和断开时的回调 & 消息回调
        _server.setConnectionCallback(std::bind(&Server::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&ProtobufCodec::onMessage, &_codec, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    void start()
    {
        LOG_INFO << "server start ...";
        _server.start();
        _base_loop.loop();
    }

private:
    // 当连接建立和断开时回调
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        LOG_INFO << conn->peerAddress().toIpPort() << " -> " << conn->localAddress().toIpPort() 
            << " is " << (conn->connected() ? "UP" : "DOWN");
    }

    // 当出现未知业务请求时，默认处理函数
    void onUnknownMessage(const muduo::net::TcpConnectionPtr& conn, const MessagePtr& message, muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown();
    }

    // 翻译请求处理函数
    void onTranslateMessage(const muduo::net::TcpConnectionPtr& conn, const TranslateRequestPtr& message, muduo::Timestamp)
    {
        LOG_INFO << "onTranslateMessage: " << message->GetTypeName();
        // 1. 获取body
        std::string msg = message->content();

        // 2. 翻译业务处理
        std::string res = translate(msg);

        // 3. 构建响应
        TranslateResponse response;
        response.set_content(res);

        // 4. 发送响应
        _codec.send(conn, response); // 发送响应并不是直接通过conn来完成，而是将响应和conn交给应用层协议来完成
    }

    // 加法请求处理函数
    void onCalculateMessage(const muduo::net::TcpConnectionPtr& conn, const CalculateRequestPtr& message, muduo::Timestamp)
    {
        LOG_INFO << "onCalculateMessage: " << message->GetTypeName();
        // 1. 获取body
        int num1 = message->num1();
        int num2 = message->num2();
        int op = message->op();

        // 2. 加法业务处理
        int res = calculator(num1, num2, op);

        // 3. 构建响应
        CalculateResponse response;
        response.set_result(res);

        // 4. 发送响应
        _codec.send(conn, response);
    }
    
private:
    // 翻译处理函数
    std::string translate(std::string msg)
    {
        std::map<std::string, std::string> dict = {{"hello", "你好"}, {"world", "世界"}, {"muduo", "muduo库"}};
        return dict[msg];
    }

    // 计算器处理函数
    int calculator(int num1, int num2, int op)
    {
        switch (op)
        {
        case '+':
            return num1 + num2;
        case '-':
            return num1 - num2;
        case '*':
            return num1 * num2;
        case '/':
            return num1 / num2;
        default:
            return 0;
        }
    }

private:
    muduo::net::EventLoop _base_loop;
    muduo::net::TcpServer _server;
    ProtobufDispatcher _dispatcher; // 消息分发器 -- 处于应用层协议之上
    ProtobufCodec _codec; // 协议处理器
};

int main()
{
    Server server(8080);
    server.start();
    return 0;
}